package com.thunder.soft.vm;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thunder.soft.bean.SystemBean;
import com.thunder.soft.common.base.BaseBean;
import com.thunder.soft.common.base.BaseViewModel;
import com.thunder.soft.common.net.HttpClient;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SystemViewModel extends BaseViewModel {
    public MutableLiveData<List<SystemBean>> liveData = new MutableLiveData<>();

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);

        HttpClient.getInstance().request("tree/json", "GET", null, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getErrorMsg().postValue(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Gson gson = new Gson();

                BaseBean<List<SystemBean>> listBaseBean = gson.fromJson(response.body().string(),
                        new TypeToken<BaseBean<List<SystemBean>>>() {
                        }.getType());

                if (listBaseBean.getErrorCode() == 0) {
                    liveData.postValue(listBaseBean.getData());
                }else {
                    getErrorMsg().postValue(listBaseBean.getErrorMsg());
                }
            }
        });
    }

    public MutableLiveData<List<SystemBean>> getLiveData() {
        return liveData;
    }
}